﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using API.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using POMain.API.Dtos;
using POMain.API.Infrastructure;
using POMain.API.ViewModel;

namespace POMain.API.Controllers
{
    [Route("api/v1/[controller]")]
    [ApiController]
    public class PODemandController : ControllerBase
    {
        private readonly PODbContext _context;

        public PODemandController(PODbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));

            _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }

        [HttpGet("paged/poinfo")]
        [ProducesResponseType(typeof(PaginatedItemsViewModel<POInfoDto>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<PaginatedItemsViewModel<POInfoDto>>> GetPagedPOInfoAsync(
            string? keyword ="",
            [FromQuery] int pageSize = 10,
            [FromQuery] int pageIndex = 0)
        {

            var query = from podetail in _context.PODetails
                         join pomain in _context.PODemands on podetail.POMainId equals pomain.Id into temp
                         from t1 in temp.DefaultIfEmpty()
                         join vaccines in _context.Vaccines on podetail.VaccineId equals vaccines.Id into temp2
                         from t2 in temp2.DefaultIfEmpty()
                         join company in _context.Companies on t1.ManufactorId equals company.Id into temp3
                         from t3 in temp3.DefaultIfEmpty()
                         join vaccinationPoints in _context.VaccinationPoints on t1.VaccinationPointId equals vaccinationPoints.Id into temp4
                         from t4 in temp4.DefaultIfEmpty()
                         select new POInfoDto {
                             Id= podetail.Id,
                             POMainId = podetail.POMainId,
                             Quantity = podetail.Quantity,
                             TotalReceiveQty = podetail.TotalReceiveQty,
                             Code = t1.Code,
                             DemandDate = t1.DemandDate,
                              ManufactorId = t1.ManufactorId,
                             CompanyName = t3.CompanyName,
                              VaccinationPointName = t4.Name,
                               VaccineCode = t2.Code,
                               VaccineName =t2.Name,
                               VaccineId =podetail.VaccineId,
                                
                         };
            if (!string.IsNullOrWhiteSpace(keyword)) {
                query = query.Where(x => x.Code.Contains(keyword) || x.CompanyName.Contains(keyword) || x.VaccinationPointName.Contains(keyword) || x.VaccineCode.Contains(keyword) || x.VaccineName.Contains(keyword));
            }
          

            var totalItems = await query
                .LongCountAsync();

            var itemsOnPage = await query
                .OrderByDescending(item => item.Code)
                .Skip(pageSize * pageIndex)
                .Take(pageSize)
                .ToListAsync();

            return new PaginatedItemsViewModel<POInfoDto>(pageIndex, pageSize, totalItems, itemsOnPage);
        }


        /// <summary>
        /// 创建疫苗需求
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("create")]
        public async Task CreateAsync(PODemandEditDto input)
        {
            if (!_context.PODemands.Any(x => x.Code == input.Code))
            {
                var mainId = Guid.NewGuid();
                var entity = new PODemand(mainId, input.Code,input.VaccinationPointId,input.ManufactorId,input.DemandDate);
                entity.Items = input.Items.Select(x=>new PODetails(Guid.NewGuid(), mainId,x.VaccineId,x.Quantity)).ToList();
                _context.Add<PODemand>(entity);
                await _context.SaveChangesAsync();
            }
            else
            {
                var entity = await _context.PODemands.Where(x => x.Code == input.Code).FirstOrDefaultAsync();
                entity.VaccinationPointId = input.VaccinationPointId;
                entity.ManufactorId = input.ManufactorId;
                entity.DemandDate = input.DemandDate;
                entity.Items = input.Items.Select(x => new PODetails(Guid.NewGuid(), entity.Id, x.VaccineId, x.Quantity)).ToList();

                _context.Update(entity);
                await _context.SaveChangesAsync();

            }
        }



     

        /// <summary>
        /// 删除疫苗需求
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("delete")]
        public async Task DeleteAsync(Guid id)
        {
            var entity = await _context.PODemands.Include(x=>x.Items).Where(x => x.Id == id).FirstOrDefaultAsync();
            if (entity != null)
            {
                if (entity?.Items?.Count > 0) {
                    _context.RemoveRange(entity.Items);
                }
                _context.Remove<PODemand>(entity);
                await _context.SaveChangesAsync();
            }
        }


        /// <summary>
        /// 删除疫苗需求明细行
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("deleteItem")]
        public async Task DeleteItemAsync(Guid id)
        {
            var entity = await _context.PODetails.Where(x => x.Id == id).FirstOrDefaultAsync();
            if (entity != null) {
                _context.Remove<PODetails>(entity);
                await _context.SaveChangesAsync();
            }
            
        }
    }



}
